package com.example.demo.zaqizabatest.sort;

import java.util.Arrays;

/**
 * @ClassName BubbleSort
 * @Author lys4134
 * @Date 2022/03/04 13:56:48
 * @Description BubbleSort
 * @Version 1.0
 **/
public class BubbleSort {

    public static void main(String[] args) {
        int[] nums = new int[]{3, 20, 9, -1, 10};
        sort(nums);
        System.out.println(Arrays.toString(nums));

        int[] nums1 = new int[]{-1,3, 9, 10, 20};
        sort1(nums1);
        System.out.println(Arrays.toString(nums1));
    }

    /**
     * 相邻两个数对比
     *
     * @param nums
     */
    public static void sort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                }
            }
        }
    }

    /**
     * 相邻两个数对比
     * 优化点：当某一次循环中没有交换位置，则结束循环
     *
     * @param nums
     */
    public static void sort1(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < nums.length - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                    flag = true;
                }
            }
            if (!flag) {
                return;
            }
        }

    }

    /**
     * 交换位置
     *
     * @param nums
     * @param i
     * @param j
     */
    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}
